<script lang="ts" setup>
import SmoothDndContainer from '@/components/SmoothDnd/SmoothDndContainer';
import SmoothDndDraggble from '@/components/SmoothDnd/SmoothDndDraggble';
import useBlocksStore from '@/store/module/blocks';
import BlockRenderer from './BlockRenderer.vue';
import { v4 as uuid } from 'uuid';
import { storeToRefs } from 'pinia';
import { DropResult } from 'smooth-dnd';
import { toRaw } from 'vue';
import { arrayMove } from '@/utils/array';

// 获取数据
const blocksStore = useBlocksStore();
const { blocks } = storeToRefs(blocksStore);
const { updateBlocks } = blocksStore;

const applyDrag = <T extends any[]>(arr: T, dragResult: DropResult) => {
  const { removedIndex, addedIndex, payload } = dragResult;

  const result = [...arr];

  // 没做操作
  if (addedIndex === null) return result;

  // 添加
  if (addedIndex !== null && removedIndex === null) {
    result.splice(addedIndex, 0, {
      id: uuid(),
      ...payload,
    });
  }

  // 移动
  if (addedIndex !== null && removedIndex !== null) {
    return arrayMove(result, removedIndex, addedIndex);
  }
   
  return arr;
};
</script>

<template>
  <SmoothDndContainer
    group-name="blocks"
    orientation="vertical"
    @drop="updateBlocks(applyDrag(toRaw(blocks), $event))"
  >
    <SmoothDndDraggble v-for="(block, index) in blocks" :key="block.id">
      <BlockRenderer :block="block" :index="index" />
    </SmoothDndDraggble>
  </SmoothDndContainer>
</template>
